# cronmon - Cron e-mail filtering and management
# Copyright (c) 2010 Crown copyright
# 
# This file is part of cronmon.
# 
# cronmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# cronmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with cronmon.  If not, see <http://www.gnu.org/licenses/>.

from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotAllowed
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.core.paginator import Paginator

def template(request, template, **kwargs):
    return render_to_response(template, kwargs, context_instance=RequestContext(request))


from models import *
from forms import *

from escalation import RT, escalate


def all_hosts_view(qs, template_name):
    def __messages(request):
        if callable(qs):
            messages = qs()
        else:
            messages = qs.all()

        pages = Paginator(messages, 50)
        try:
            page = pages.page(int(request.GET.get('page', '1')))
        except:
            page = pages.page(1)

        messages = page.object_list

        return template(request, template_name, messages=messages, page=page, pages=pages)

    return __messages


todays_messages = all_hosts_view(Message.objects.today, 'cron/today.html')
new_messages = all_hosts_view(Message.objects.new(), 'cron/new.html')
critical_messages = all_hosts_view(Message.objects.critical(), 'cron/critical.html')
warning_messages = all_hosts_view(Message.objects.warning(), 'cron/warning.html')


def message(request, id):
    message = get_object_or_404(Message, id=id)
    log = message.messagestatuslog_set.all()

    if request.method == 'POST':
        if 'escalate' in request.POST:
            escalate(message)
        elif 'undiscard' in request.POST:
            message.status = '-'
            message.save()
            message.add_log_message('Restored by administrator', type='discard')
        elif 'discard' in request.POST:
            message.discard()
            message.add_log_message('Discarded by administrator', type='discard')
        return HttpResponseRedirect(request.path)

    return template(request, 'cron/message.html', message=message, log=log)


def discard_message(request, id):
    message = get_object_or_404(Message, id=id)

    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    if message.status != '-':
        return HttpResponseRedirect(message.get_absolute_url())

    message.discard()
    message.add_log_message('Discarded by administrator', type='discard')

    return HttpResponseRedirect('/')


def escalate_message(request, messageid):
    """Display a form for re-emailing a message to RT"""
    message = get_object_or_404(Message, id=messageid)
    if message.status == 'E':
        return HttpResponseRedirect(message.get_absolute_url())

    escalate(message)
    return HttpResponseRedirect(message.get_absolute_url())


def by_host(request, hostname):
    host = get_object_or_404(Host, name=hostname)
    messages = Message.objects.new().filter(host=host)

    pages = Paginator(messages, 50)
    try:
        page = pages.page(int(request.GET.get('page', '1')))
    except:
        page = pages.page(1)

    messages = page.object_list

    return template(request, 'cron/by-host.html', host=hostname, messages=messages, page=page, pages=pages)


def by_tag(request, tag):
    tag = get_object_or_404(Tag, name=tag)
    messages = Message.objects.new().filter(tags=tag)

    pages = Paginator(messages, 50)
    try:
        page = pages.page(int(request.GET.get('page', '1')))
    except:
        page = pages.page(1)

    messages = page.object_list

    return template(request, 'cron/by-tag.html', tag=tag, messages=messages, page=page, pages=pages)


def all_hosts(request):
    hosts = Host.objects.all()
    return template(request, 'cron/all-hosts.html', hosts=hosts)

def all_tags(request):
    tags = Tag.objects.all()
    return template(request, 'cron/all-tags.html', tags=tags)
    

def escalate_message2(request, messageid):
    """Display a form for re-emailing a message to RT"""
    message = get_object_or_404(Message, id=messageid)
    if message.status == 'E':
        return HttpResponseRedirect(message.get_absolute_url())
            
    if request.method == 'POST':
        form = EscalateMessageForm(message, request.POST)
        if form.is_valid():
            #TODO: send message
            return HttpResponseRedirect(message.get_absolute_url())
    else:
        form = EscalateMessageForm(message)

    return template(request, 'cron/escalate-message.html', message=message, form=form)
